package com.example.Service.impl;

import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.vo.system.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.Mapper.SysRoleMapper;
import com.example.Mapper.SysUserRoleMapper;
import com.example.Service.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
   @Resource
   private SysUserRoleMapper sysUserRoleMapper;
    public Map<String, Object> findRoleByUserId(Integer userId){
        List<SysRole> list=this.list();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
        lambdaQueryWrapper.select(SysUserRole::getRoleId);
        List<SysUserRole> list1=sysUserRoleMapper.selectList(lambdaQueryWrapper);
        List<Long> list2=list1.stream().map(c->c.getRoleId()).collect(Collectors.toList());
        List<SysRole> assignRoleList=new ArrayList<>();
        for (SysRole sysRole:list){
            if(list2.contains(sysRole.getId())){
                assignRoleList.add(sysRole);
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("assginRoleList",assignRoleList);
        map.put("allRolesList",list);
        return map;



    }
    public     void doAssign(AssginRoleVo assginRoleVo){
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        lambdaQueryWrapper.select(SysUserRole::getRoleId);

        List<SysUserRole> list=sysUserRoleMapper.selectList(lambdaQueryWrapper);
        System.out.println(list+"list");
        List<Long> list1=list.stream().map(c->c.getRoleId()).collect(Collectors.toList());
        for (Long i:list1){
            LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
            sysUserRoleMapper.delete(lambdaQueryWrapper1);

        }
        for (Long i:assginRoleVo.getRoleIdList()){
            if(StringUtils.isEmpty(i)) continue;
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setRoleId(i);
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRoleMapper.insert(sysUserRole);
        }

    }
}
